package com.wgc.search.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;


import com.wgc.entity.Result;


import com.wgc.goods.domain.Detail;
import com.wgc.goods.feign.DetailFeign;
import com.wgc.search.DetailIndex;
import com.wgc.search.dao.ESManagerMapper;
import com.wgc.search.service.ESManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


@Service
public class ESManagerServiceImpl implements ESManagerService {
    @Autowired
    private ESManagerMapper esManagerMapper;
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;
    @Autowired
    private DetailFeign goodsFeign;


    @Override
    public void createMappingAndIndex() {
        //创建索引
        elasticsearchTemplate.createIndex(DetailIndex.class);
        //创建映射
        elasticsearchTemplate.putMapping(DetailIndex.class);

    }

    @Override
    public void importById(String id) {
        Map map = new HashMap();
        map.put("client_secret", "123456");
        map.put("client_id", "itbuka");
        map.put("grant_type", "client_credentials");
        String post = HttpUtil.post("http://localhost:9200/oauth/token", map);
        Map token = JSONObject.parseObject(post, Map.class);
        String accessToken = token.get("access_token").toString();
        Map headers = new HashMap();
        headers.put("Authorization", "Bearer " + accessToken);
        Map param = new HashMap();
        param.put("id", id);
        String body = HttpUtil.createGet("http://localhost:9001/detail/findDetail").addHeaders(headers).form(param).execute().body();
        //获取商品数据
        Detail data = JSON.parseObject(JSONObject.parseObject(body, Result.class).getData().toString(), Detail.class);

//        Map<String, Object> dataMap = JSON.parseObject(body, Map.class);
//        Detail data = goodsFeign.findDetail(Long.valueOf(id)).getData();
        //商品转成索引类型
        DetailIndex detailIndex = JSONObject.parseObject(JSON.toJSONString(data), DetailIndex.class);
        //保存索引库
        esManagerMapper.save(detailIndex);

    }

    @Override
    public void deleteById(String id) {
        esManagerMapper.deleteById(id);
    }
}
